<template>
	<div class="app-container">
		<!-- 搜索条件 -->
		<!-- <el-form :model="formData" :inline="true" :label-width="100">
			<el-row>
				<el-form-item label="业务系统" prop="systemId">
					<yd-select
						ref="systemRef"
						:config="{
							placeholder: '请选择业务系统',
							api: { name: 'queryDefaultAppSystemOptions', params: {} },
							selectKey: 'id',
							allOption: false,
							multiple: false,
							selectFirst: true,
						}"
						v-model="formData.systemId"
						@selectValChange="handleSelectChange('segmentIds')"
					></yd-select>
				</el-form-item>
				<el-form-item label="告警网端" prop="segmentIds">
					<yd-select
						:config="{
							placeholder: '请选择告警网端',
							api: {
								name: 'querySegmentBySystemId',
								params: formData.systemId,
							},
							selectKey: 'id',
							allOption: true,
							multiple: true,
							cascaderParam: formData.systemId,
						}"
						@selectInited.once="formInited"
						v-model="formData.segmentIds"
					></yd-select>
				</el-form-item>
				<el-form-item label="告警分类" prop="alarmStates">
					<yd-select
						:config="{
							placeholder: '请选择告警分类',
							data: [
								{ value: '0', label: '失败告警' },
								{ value: '1', label: '普通告警' },
							],
							selectKey: 'value',
							allOption: true,
							multiple: true,
						}"
						v-model="formData.alarmStates"
					></yd-select>
				</el-form-item>

				<el-form-item label="告警类型" prop="alarmIndicatorIds">
					<yd-select
						:config="{
							placeholder: '请选择告警类型',
							api: {
								name: 'queryBaseIndicatorsList',
								params: { category: 'apm' },
							},
							selectKey: 'id',
							allOption: true,
							multiple: true,
						}"
						v-model="formData.alarmIndicatorIds"
					></yd-select>
				</el-form-item>

				<el-form-item label="告警级别" prop="alarmLevelIds">
					<yd-select
						:config="{
							placeholder: '请选择级别',
							api: { name: 'queryAlarmLevel', params: {} },
							allOption: true,
							multiple: true,
							selectKey: 'id',
						}"
						v-model="formData.alarmLevelIds"
					></yd-select>
				</el-form-item>
				<el-form-item prop="" label="业务名称">
					<el-input v-model="formData.businessName" placeholder="输入业务名称模糊查询"></el-input>
				</el-form-item>
				<el-form-item prop="" label="专属指标">
					<el-input v-model="formData.exclusiveIndicator" placeholder="输入专属指标查询"></el-input>
				</el-form-item>
				<el-form-item prop="" label="告警对象">
					<el-input v-model="formData.alarmObject" placeholder="输入告警对象查询"></el-input>
				</el-form-item>
			</el-row>
			<el-form-item prop="" label="时间范围">
				<yd-time-range
					:config="{
						enableCrossDay: true,
						defaultValue: 'last1h',
						enableCrossDay: true,
					}"
					@pickChange="handlePickChange"
					ref="timeRange"
				></yd-time-range>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" icon="Search" @click="searchHandler">查 询</el-button>
				<el-button style="margin-left: 15px" type="primary" @click="downloadHandler">下载</el-button>
				<el-button style="margin-left: 15px" type="primary" @click="showInitDialog">自定义列</el-button>
			</el-form-item>
		</el-form> -->
		<yd-form class="yd-form-wraper" :options="formOptions" :model="formData" @form-init="formInited" @search="formInited">
			<template #form-btn>
				<el-button type="primary" icon="Search" @click="searchHandler">查 询</el-button>
				<el-button style="margin-left: 15px" type="primary" :disabled="!tableData.data.length" @click="downloadHandler">下载</el-button>
				<el-button style="margin-left: 15px" type="primary" @click="showInitDialog">自定义列</el-button>
			</template>
		</yd-form>

		<div v-if="dataForm.relvanceDataId != null" class="relvanceDataIdClass">附加条件的数据id：{{ dataForm.relvanceDataId }}</div>

		<!-- 基础告警列表(NPM) -->
		<YdCard>
			<YdTable
				:formData="formData"
				:tableConfig="tableConfig"
				:tableData="tableData.data"
				@sizeChangeHandler="queryGridByCloneData1"
				@currentChangeHandler="queryGridByCloneData"
				@sortChangeHandler="queryGridByCloneData"
			></YdTable>
		</YdCard>

		<!-- 自定义列弹出层 -->
		<custom-column ref="customColumnRef" pageType="apmAlarm"></custom-column>
	</div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router';
import { getBaseAlarmList, exportBaseAlarmExcel } from '@/api/bpm/alarm/busi_detail_alarm';
import { parseTime } from '@/utils/common';
import CustomColumn from '@/components/CustomColumn/index.vue';
import useUserStore from '@/store/modules/userinfo';

import { onMounted, ref, reactive, getCurrentInstance, onActivated, nextTick } from 'vue';
const instance = getCurrentInstance();
const proxy = instance?.proxy;

const route = useRoute();
const customColumnRef = ref<InstanceType<typeof CustomColumn>>();
const dataForm = reactive({
	relvanceDataId: null,
});
// 搜索表单数据

// 表单配置
const formOptions = ref<FormOptionType>([
	{
		type: 'select',
		prop: 'systemId',
		label: '业务系统',
		api: {
			name: 'queryAppSystemOptions',
			params: { isStatus: 1 },
		},
		cascaders: [
			{
				cascadersParams: 'segmentIds',
				api: {
					name: 'querySegmentOptions',
				},
			},
		],
	},
	{
		type: 'select',
		prop: 'segmentIds',
		label: '告警网端',
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'alarmStates',
		label: '告警分类',
		attrs: {
			multiple: true,
		},
		children: [
			{
				label: '失败',
				value: '0',
			},
			{
				label: '普通',
				value: '1',
			},
		],
	},
	{
		type: 'select',
		prop: 'alarmIndicatorIds',
		label: '告警类型',
		api: {
			name: 'queryBaseIndicatorsOptions',
			params: {
				category: 'NPM',
			},
		},
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		prop: 'alarmLevelIds',
		label: '告警级别',
		api: {
			name: 'queryAlarmLevelOptions',
		},
		attrs: {
			multiple: true,
		},
	},

	{
		type: 'input',
		prop: 'businessName',
		label: '业务名称',
	},
	{
		type: 'input',
		prop: 'exclusiveIndicator',
		label: '专属指标',
	},
	{
		type: 'input',
		prop: 'alarmObject',
		label: '告警对象',
	},
	{
		type: 'date-picker',
		prop: 'dateRange',
		span: 8,
		dateType: 'datetimerange',
		label: '时间范围',
		enableCrossDay: true,
	},
]);

// 格式化query
let formData = reactive<FormModelType>({
	category: 'NPM',
	segmentIds: [''], //告警网端
	alarmIndicatorIds: [''],
	alarmLevelIds: [''],
	alarmStates: [''],
});
let cloneFormData: FormModelType = {};
const cloneHeaderFormData: FormModelType = ref({});
// 列表配置
const tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '告警对象',
			prop: 'alarmObject',
			align: 'left',
			hide: true,
			width: 150,
		},
		{
			label: '所属网端',
			prop: 'segmentName',
			hide: false,
			width: 150,
		},
		{
			label: '所属系统',
			prop: 'systemName',
			hide: false,
			width: 150,
		},
		{
			label: '告警级别',
			prop: 'alarmLevelName',
			hide: false,
			width: 90,
		},
		{
			label: '告警现象',
			prop: 'alarmContext',
			hide: false,
			width: 800,
		},
		{
			label: '告警类型',
			prop: 'alarmIndicatorName',
			hide: false,
			width: 150,
		},
		{
			label: '告警时间',
			prop: 'alarmTriggerTime',
			sortable: true,
			// hide: false,
			width: 200,
		},
		{
			label: '请求IP端口',
			prop: 'requestIpPort',
			hide: true,
			width: 170,
			formatter: (row, val) => {
				return row.requestIp + ':' + row.requestPort;
			},
		},
		{
			label: '响应IP端口',
			prop: 'responseIpPort',
			hide: true,
			width: 170,
			formatter: (row, val) => {
				return row.responseIp + ':' + row.responsePort;
			},
		},
		{
			label: '专属指标',
			prop: 'exclusiveIndicator',
			hide: true,
			isExclusive: true,
			width: 150,
		},
	],
	pagination: {
		pageNum: 1,
		orderByColumn: 'alarmTriggerTime',
	},
	loading: true,
});
// 列表数据
const tableData = reactive({
	data: [],
	total: 0,
});
const fromRule = reactive({
	queryColumnValue: [{ required: true, message: '不能为空', trigger: 'blur' }],
});
const downloadStartTime = ref('');
const downloadEndTime = ref('');
const options = ref<anyObj[]>([]);
const downloading = ref(false);
initQuery(route.query, formData);
onMounted(() => {
	dataForm.relvanceDataId = formData.relvanceDataId;

	customColumnRef.value?.useCustomColumn('bpm3.customField.businessAlarmList.apm', tableConfig.columns);
});

// onActivated(() => {});
// 格式化传过来的参数
function initQuery(query: anyObj, formData: FormModelType) {
	if (!query.category || query.category === 'BPM') {
		return false;
	}
	try {
		let data = JSON.parse(query.data);
		for (let key in data) {
			formData[key] = data[key];
		}
	} catch {
		for (let key in query) {
			formData[key] = query[key];
		}
	}
	if (formData.systemId) {
		formData.systemId = String(formData.systemId);
	}
	if (formData.alarmIndicatorIds) {
		formData.alarmIndicatorIds = formData.alarmIndicatorIds.map((item: any) => String(item));
	}
	if (formData.alarmLevelIds) {
		formData.alarmLevelIds = formData.alarmLevelIds.map((item: any) => String(item));
	}
	if (formData.alarmStates) {
		formData.alarmStates = formData.alarmStates.map((item: any) => String(item));
	}
}

// 表单初始化完毕
function formInited() {
	initQuery(route.query, formData);
	tableConfig.pagination!.pageNum = 1;
	searchHandler(2);
}
// 搜索
function searchHandler(flag: any) {
	//
	//当用户点击搜索的时候清空数据id
	if (flag !== 2) {
		dataForm.relvanceDataId = null;
		formData.relvanceDataId = null;
	}
	let start = formData.startTime;
	let end = formData.endTime;
	//点击自定义的时候将清理startTime和endTime
	if (start === null || end === null) {
		proxy?.$message.warning('开始和结束时间不能为空');
		tableConfig.loading = false;
		return;
	} else {
		//最近一小时跨天问题，以结束时间，如果最近一小时存在跨天，比如当前时间为2020-11-05 00:08:00，
		// 那么startTime="2020-11-05 00:00:00"  endTime="2020-11-05 00:08:00"。
		let startFormat = parseTime(start, '{y}-{m}-{d}');
		let endFormat = parseTime(end, '{y}-{m}-{d}');
		let endTime = new Date(end);
		let sumTime = endTime.getHours() + endTime.getMinutes() + endTime.getSeconds();
		let old_time = new Date(endFormat.replace(/-/g, '/'));
		let new_time = new Date(old_time.getTime() - 24 * 3600 * 1000);
		let new_format = parseTime(new_time, '{y}-{m}-{d}');
		// if (
		//   startFormat != endFormat &&
		//   (startFormat != new_format || sumTime != 0)
		// ) {
		//   proxy.$message.warning("开始和结束时间不能跨天");
		//   tableConfig.loading = false;
		//   return;
		// }
	}
	formData.startTime = start;
	formData.endTime = end;
	queryGrid();
}

// 去掉空字符串""
function sliceEmptyString(formData: any) {
	for (let key in formData) {
		if (formData[key] instanceof Array) {
			if (formData[key].length === 1 && formData[key][0] === '') {
				formData[key] = [];
			}
		} else {
			if (formData[key] === '') {
				delete formData[key];
			}
		}
	}
	return formData;
}

// 查询列表数据
function queryGrid(cloneDataFlag?: any) {
	let data = null;
	if (cloneDataFlag) {
		data = {
			...formData,
		};
	} else {
		// 深复制
		data = {
			...JSON.parse(JSON.stringify(formData)),
		};
		cloneHeaderFormData.value = JSON.parse(JSON.stringify(data));
	}
	downloadStartTime.value = data.startTime;
	downloadEndTime.value = data.endTime;
	tableConfig.loading = true;

	sliceEmptyString(data);
	getBaseAlarmList(data).then((res: ApiResponse) => {
		tableConfig.loading = false;
		if (res.code !== 0) {
			proxy?.$message.warning(res.msg);
			return;
		}
		tableConfig.loading = false;
		tableData.data = res.data.data;
		tableConfig.pagination!.total = res.data.total;
		if (!(res.msg === 'success')) {
			proxy?.$message.warning(res.msg);
		}
	});
}
function queryGridByCloneData() {
	queryGrid(true);
}
function queryGridByCloneData1() {
	formData.pageNum = 1;
	queryGrid(true);
}
// 下载
function downloadHandler() {
	formData.startTime = downloadStartTime;
	formData.endTime = downloadEndTime;
	let list = [];
	let new_list = [];
	for (let i of tableConfig.columns) {
		if (!i.hide) {
			list.push(i.label);
			new_list.push(i.prop);
		}
	}
	formData.displayMappingFields = new_list;
	formData.displayFields = list;
	formData.orderByColumn = cloneHeaderFormData.value.orderByColumn;
	formData.isAsc = cloneHeaderFormData.value.isAsc;
	for (let i of options.value) {
		if (formData.systemId === i.id) {
			formData.systemName = i.label;
		}
	}
	let data = {
		submitterId: useUserStore().userInfo?.userId,
		submitterName: useUserStore().userInfo?.username,
		submitTime: parseTime(new Date()),
		serviceCode: 'business-monitor',
		moduleName: 'BPM_WEB_MAIN',
		exportBtnName: '基础告警NPM列表下载',
		docExportParameterJson: JSON.stringify(formData),
		exportFileName: '基础告警NPM列表.xlsx',
		docHandleType: '2',
	};
	exportBaseAlarmExcel(data).then((res) => {
		proxy?.$message.success('已加入下载队列，请查看＂↓＂');
	});
}
// 自定义列点击事件
function showInitDialog() {
	customColumnRef.value?.handleOpen('bpm3.customField.businessAlarmList.apm', tableConfig.columns);
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
:deep(.el-icon-edit-outline) {
	background: url('@/assets/icons/png/edit.png') no-repeat;
	background-size: 18px;
	&:before {
		content: '';
		font-size: 16px;
		visibility: hidden;
	}
}
.el-form-item__label {
	line-height: 36px;
}
:deep(.el-dialog__header .el-dialog__title) {
	background-image: url('@/assets/images/bpm/dialog/init-title.png');
	background-repeat: no-repeat;
	background-position: center;
	background-size: 100% 100%;
	color: #ffffff;
	font-size: 16px;
	display: inline-block;
	width: 215px;
	padding-left: 5px;
}
:deep(.el-checkbox__input.is-checked) {
	background-color: #06cbcb;
}
.style-split-yd-card {
	:deep(.el-card) {
		background-color: rgba(29, 39, 75, 0.31);
		border: unset;
		border-radius: 12px;
	}
}
</style>
